package com.xutong.myfunction.socket;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPSocketServer extends Thread{

	private static final int SERVER_PORT = 5000;
	ServerSocket serverSocket = null;
	Socket socket = null;
	public static boolean run = false;
	public TCPSocketServer(){
		
	}
	
	/**
	 * 设置服务器开关
	 * @param b
	 */
	public void setOnOff(boolean b){
		this.run = b;
	}
	
	@Override
	public void run() {
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		OutputStream os = null;
		PrintWriter pw = null;
		StringBuffer sb;
		try {
			serverSocket = new ServerSocket(SERVER_PORT);
			System.out.println("服务端已经启动，等待客户端请求");
			while(run){
				sb = new StringBuffer();
				socket = serverSocket.accept();
				is = socket.getInputStream();
				isr = new InputStreamReader(is);
				br = new BufferedReader(isr);
				Log.e("ServerSocket","服务器在这运行");
				String info = null;
				while((info=br.readLine())!=null){
//					System.out.println("我是服务端，客户端发送的信息是："+info);
					sb.append(info).append("\n");
				}

				socket.shutdownInput();

				os = socket.getOutputStream();
				pw = new PrintWriter(os);
				pw.write("我是服务端，客户端发送的信息是："+sb.toString());
				pw.flush();

				if(pw!=null)
					pw.close();
				if(os!=null)
					os.close();
				if(br!=null)
					br.close();
				if(isr!=null)
					isr.close();
				if(is!=null)
					is.close();
				if(socket!=null)
					socket.close();

			}
			if(serverSocket!=null)
					serverSocket.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("服务端异常："+e.getMessage());
		}
	}
		
	
}
